/**
 * Created by li.zhixiong on 2018/3/21.
 */
import router from '../router'
import axios from 'axios'
import Vue from 'vue'

var qs = require('qs')

const errInfoTips = (MessageType, Message) => {
  new Vue().$notify({
    title: '提示',
    message: Message,
    position: 'bottom-right',
    showClose: false,
    type: 'warning'
  })
  if (MessageType === '401') {
    router.push({path: '/login'})
    window.localStorage.clear()
  } else if (MessageType === '1') {
    console.warn('警告:' + Message)
  } else if (MessageType === '2') {
    console.warn('失败:' + Message)
  } else if (MessageType === '3') {
    console.warn('错误:' + Message)
  } else if (MessageType === '4') {
    console.warn('异常:' + Message)
  }
}

let RequestMethod = {
  'GET': 'GET',
  'HEAD': 'HEAD',
  'POST': 'POST',
  'PUT': 'PUT',
  'PATCH': 'PATCH',
  'DELETE': 'DELETE',
  'DOWNLOAD': "DOWNLOAD"
}

// http request 拦截器
// MessageType： 响应操作的结果类型，0成功，1警告，2失败，3错误，4异常
// MessageCode： 响应的消息代码，-1为成功，0-500为以后扩展错误的详细代码
axios.interceptors.request.use(
  config => {
    if (window.localStorage.token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.token = `${window.localStorage.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)
const Utils = {
  httpUtil (url, data, config = {}, type) {
    return new Promise((resolve, reject) => {
      let axiosTemp
      switch (type) {
        case RequestMethod.DELETE:
          axiosTemp = axios.delete(url, config)
          break
        case RequestMethod.HEAD:
          axiosTemp = axios.head(url, config)
          break
        case RequestMethod.PATCH:
          axiosTemp = axios.patch(url, data, config)
          break
        case RequestMethod.POST:
          axiosTemp = axios.post(url, data, config)
          break
        case RequestMethod.PUT:
          axiosTemp = axios.put(url, data, config)
          break
        default:
          axiosTemp = axios.get(url, config)
      }
      axiosTemp.then(function (response) {
        let MessageType = response.data.messageType
        let Message = response.data.message

        if (!MessageType || MessageType === '0') { // 成功
          resolve(response)
        } else {
          errInfoTips(MessageType, Message)
          resolve(response)
        }
      }).catch(function (error) {
        reject(error)
        console.log(error)
      })
    })
  },
  get (url, data = {}) {
    return Utils.httpUtil(url, null, {
      params: data,
      withCredentials: true
    }, RequestMethod.GET)
  },
  post (url, data = {}) {
    return Utils.httpUtil(url, qs.stringify(data), {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }, RequestMethod.POST)
  },
  postlogin (url, data = {}) {
    return Utils.httpUtil(url, qs.stringify(data), {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Authorization': 'Basic d2ViOjEyMzQ1Ng=='
      }
    }, RequestMethod.POST)
  },
  postJSON (url, data = {}) {
    return Utils.httpUtil(url, JSON.stringify(data), {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }, RequestMethod.POST)
  },
  postFile (url, data = {}) {
    return Utils.httpUtil(url, data, {
      withCredentials: true,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }, RequestMethod.POST)
  },
  delete (url, data = {}) {
    return Utils.httpUtil(url, null, {
      params: data,
      withCredentials: true
    }, RequestMethod.DELETE)
  },
  put (url, data = {}) {
    return Utils.httpUtil(url, qs.stringify(data), {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    }, RequestMethod.PUT)
  },
  putJSON (url, data = {}) {
    return Utils.httpUtil(url, JSON.stringify(data), {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      }
    }, RequestMethod.PUT)
  },
  // 在用axios，get一下这个json，build目錄下 webpack.prod.conf.js文件
  getConfigJson () {
    axios.get('serverconfig.json').then((result) => {
      console.log('read from json')
      console.log(result)
    }).catch((error) => {
      console.log(error)
    })
  },
  download(url, data = {}) {
    return Utils.httpUtil(
      url,
      qs.stringify(data), {
        responseType: 'blob',
        withCredentials: true,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
        }
      },
      RequestMethod.POST
    );
  }
}
export default Utils
